#include "util_gametimer.h"
#include <windows.h>

//----------------CONSTRUCTORS----------------------------------------------------------

LJMUUtilGameTimer::LJMUUtilGameTimer(): _prop_resolution(0.0),
										_frame_delta(-1.0), 
										_time_base(0), 
										_time_elapsed_pause(0), 
										_time_elapsed_prev(0),
										_time_elapsed_curr(0),
										_state_is_stopped(false)
{
	__int64 tcounter_resolution;
	QueryPerformanceFrequency((LARGE_INTEGER*)&tcounter_resolution);
	_prop_resolution = 1.0 / (double)tcounter_resolution;
}

//----------------PUBLIC METHODS--------------------------------------------------------


void LJMUUtilGameTimer::resetTimer()
{
	__int64 tcurrent_time;
	QueryPerformanceCounter((LARGE_INTEGER*)&tcurrent_time);

	_time_base			= tcurrent_time;
	_time_elapsed_prev	= tcurrent_time;
	_time_stopped		= 0;
	_state_is_stopped	= false;
}

void LJMUUtilGameTimer::startTimer()
{
	__int64 ttime_current;
	QueryPerformanceCounter((LARGE_INTEGER*)&ttime_current);

	if(_state_is_stopped)
	{
		_time_elapsed_pause += (ttime_current - _time_stopped);	
		_time_elapsed_prev	= ttime_current;
		_time_stopped		= 0;
		_state_is_stopped	= false;
	}
}

void LJMUUtilGameTimer::stopTimer()
{
	if(!_state_is_stopped)
	{
		__int64 ttime_current;
		QueryPerformanceCounter((LARGE_INTEGER*)&ttime_current);

		_time_stopped		= ttime_current;
		_state_is_stopped   = true;
	}
}

void LJMUUtilGameTimer::updateTimer()
{
	if(_state_is_stopped)
	{
		_frame_delta = 0.0;
		return;
	}

	__int64 tcurrenttime;
	QueryPerformanceCounter((LARGE_INTEGER*)&tcurrenttime);
	_time_elapsed_curr = tcurrenttime;

	// Time difference between this frame and the previous.
	_frame_delta = (_time_elapsed_curr - _time_elapsed_prev)*_prop_resolution;

	// Prepare for next frame.
	_time_elapsed_prev = _time_elapsed_curr;

	if(_frame_delta < 0.0)
		_frame_delta = 0.0;
}

